/* eslint-disable  */
import { Device, GatewayType } from "@/api/interface/iot";
import { getDevice, sendFunc } from "@/api/modules/iot/device";
import modbus from "@/assets/images/iot/snapshot/5.png";
import { useDialog } from "@/hooks/useDialog";
import { showMsg, showTips } from "@/utils/util";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { MessageType } from "@/enums/messageEnum";
import { getGatewayList } from "@/api/modules/iot/gateway";
import { getProductList } from "@/api/modules/iot/product";
import { defineComponent, onMounted, PropType, reactive } from "vue";
import { useRoute } from "vue-router";
import "../../model.scss";
import "./index.scss";
import { getProfile } from "@/api/modules/model/profile";
import { SchemaNodeKey } from "@/utils/constants";
import DialogBox from "@/components/DialogBox";
import { formatSizeAndUnit } from "@/utils/format";

export default defineComponent({
	name: "Hmp", // 动态引入需要
	label: "Hmp", // 动态引入需要
	image: modbus, // 动态引入需要
	props: {
		isHmp: Boolean,
		is6210: Boolean,
		detail: {
			type: Object as PropType<Device.ResDeviceInfo | Device.ResProduct | any>,
			default() {
				return {};
			}
		}
	},
	emit: ["reload"],
	setup(props, { emit, expose }) {
		const route = useRoute();
		const { gatewayDialog, productDialog } = useDialog();

		const state = reactive({
			syncLoading: false,
			detail: {} as any
		});

		const profile = inject<any>(SchemaNodeKey.profile);
		//初始化设备信息
		const initDevice = async () => {
			if (route.query.sn) {
				let { result, code } = await getDevice({ idSn: route.query.sn });
				if (code == 200) {
					state.detail = result;
				} else {
					showMsg("未找到相关数据", MessageType.error);
				}
			} else if (props.detail) {
				state.detail = JSON.parse(JSON.stringify(props.detail as Device.ResDeviceInfo));
			}
			if (!profile.value?.devSn && state.detail.sn) {
				const { result, code } = await getProfile({ idSn: state.detail.sn });
				if (code == 200) {
					profile.value = result;
				}
			}

			let sensor = profile.value?.profile?.sensor || {};
			Object.entries(sensor).forEach((v: any[]) => {
				let key = v[0] as string;
				key = key.toLowerCase();
				if (key == "sn") {
					return;
				}
				state.detail[key] = v[1];
			});
		};
		onMounted(() => {
			initDevice();
		});

		const basicDialog = reactive({
			title: "修改设备基本信息",
			visible: false
		});
		const setAddressDialog = reactive({
			title: "修改设备位置信息",
			visible: false
		});
		//按钮事件
		const handleFn = function (fn: String) {
			switch (fn) {
				case "sync":
					//召测
					syncData();
					break;
				case "config":
					//配置管理-显示弹框
					configDialog.fileType = "/tmp/hdconfig/cli.conf";
					configDialog.visible = true;
					break;
				case "gotoGateway":
					loadGateway();
					break;
				case "gotoProduct":
					loadProduct();
					break;
				case "updateLocation":
					setAddressDialog.visible = true;
					break;
			}
		};
		const loadGateway = async () => {
			let { result } = await getGatewayList({ sn: state.detail.gatewaySn, pageIndex: 1, pageSize: 1 }, GatewayType.SoftGateway);
			if (result.records?.[0]?.sn) {
				gatewayDialog.detail = result.records?.[0];
				gatewayDialog.visible = true;
			} else {
				showMsg("网关不存在", false);
			}
		};
		const loadProduct = async () => {
			let { result } = await getProductList({
				model: state.detail.productModel,
				deviceType: "device",
				pageIndex: 1,
				pageSize: 1
			});
			if (result.records?.[0]?.id) {
				productDialog.detail = result.records?.[0];
				productDialog.visible = true;
			} else {
				showMsg("产品不存在", false);
			}
		};
		const syncData = () => {
			state.syncLoading = true;
			sendFunc({
				idSn: props.detail.sn,
				funcName: "property/GET",
				data: {
					input: {
						GET: {}
					}
				},
				latency: 15
			}).then((res: any) => {
				state.syncLoading = false;
				let ok = showTips(res.code, "同步数据操作", res.message);

				let deviceInfo = JSON.parse(JSON.stringify(props.detail as Device.ResDeviceInfo));
				Object.entries(res.result || {}).forEach((v: any[]) => {
					let key = v[0] as string;
					key = key.toLowerCase();
					if (key == "sn") {
						return;
					}
					deviceInfo[key] = v[1];
				});
				state.detail = deviceInfo;
			});
			setTimeout(() => {
				if (state.syncLoading) {
					state.syncLoading = false;
				}
			}, 20 * 1000);
		};
		const getConfig = () => {
			configDialog.loading = true;
			configDialog.loadingText = "正在查询数据...";
			sendFunc({
				idSn: props.detail.sn,
				funcName: "property/GET",
				data: {
					input: {
						GET: {
							config: {
								cli: {}
							}
						}
					}
				},
				latency: 15
			}).then((res: any) => {
				configDialog.loading = false;
				if (res.code != 200) {
					showMsg(res.message, false);
					return;
				}
				configDialog.fileContent = res.result?.config?.cli;
			});
			setTimeout(() => {
				if (configDialog.loading) {
					configDialog.loading = false;
				}
			}, 20 * 1000);
		};
		const sendConfig = () => {
			configDialog.loading = true;
			configDialog.loadingText = "正在配置参数...";
			sendFunc({
				idSn: props.detail.sn,
				funcName: "property/SET",
				data: {
					input: {
						SET: {
							config: {
								cli: configDialog.fileContent.concat("\n!\r\nwrite file\r\n")
							}
						}
					}
				},
				latency: 15
			}).then((res: any) => {
				configDialog.loading = false;
				let ok = showTips(res.code, "配置參數", res.message);
				if (ok) {
					configDialog.visible = false;
				}
			});
			setTimeout(() => {
				if (configDialog.loading) {
					configDialog.loading = false;
				}
			}, 20 * 1000);
		};
		const configDialog = reactive({
			loading: false,
			loadingText: "",
			visible: false,
			fileType: "",
			fileContent: ""
		});
		expose({ handleFn });
		return () => {
			return (
				<div class="hmp-detail-page" v-loading={state.syncLoading} element-loading-text="正在同步数据...">
					<DialogBox v-model:visible={configDialog.visible} title="配置管理" onConfirm={sendConfig} width="600px">
						<div class="flex">
							<el-select
								class="flex-1"
								v-model={configDialog.fileType}
								allow-create
								filterable
								onBlur={(e: Event) => (configDialog.fileType = (e.target as HTMLInputElement).value)}
							>
								<el-option value="/tmp/hdconfig/cli.conf" label="cli.conf"></el-option>
								{/* <el-option value="/tmp/message" label="message"></el-option> */}
							</el-select>
							<el-button onClick={getConfig} v-loading={state.syncLoading}>
								查询
							</el-button>
						</div>
						<div class="mt-2" v-loading={configDialog.loading} element-loading-text={configDialog.loadingText}>
							<el-input type="textarea" style="height:50vh" v-model={configDialog.fileContent}></el-input>
						</div>
					</DialogBox>
					<div class="block-content">
						<Basics detail={state.detail} onLoadMore={handleFn} />
					</div>
					<div class="block-content mt-2">
						<Network detail={state.detail} onLoadMore={handleFn} />
					</div>
					<div class="block-content mt-2">
						<System detail={state.detail} onLoadMore={handleFn} />
					</div>
				</div>
			);
		};
	}
});
const Basics = defineComponent({
	props: {
		detail: {
			type: Object as PropType<{ [key: string]: any } | any>,
			default() {
				return {};
			}
		}
	},
	emits: ["loadMore"],
	setup(props, { emit }) {
		return () => {
			return (
				<>
					<div class="flex justify-between items-center">
						<span class="block-title">基本信息</span>
					</div>
					<div class="grid grid-cols-3">
						<div class="flex item">
							<div class="info-title text-right w-1/3">设备SN</div>
							<div class="info-text inline-flex items-center">
								<span class="mr-4">{props.detail.sn}</span>
								<OnlineStatus v-model={props.detail.onlineStatus} />
							</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">设备名称</div>
							<div class="info-text">{props.detail.name}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">所属分组</div>
							<div class="info-text">{props.detail.deptName}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">信号强度</div>
							<div class="info-text">
								{props.detail?.modem?.find((item: any) => (item ? true : false))?.csq || props.detail.signal}
							</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">末次交互</div>
							<div class="info-text">{props.detail.lastLiveTime}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">末次登录</div>
							<div class="info-text">{props.detail.logoutTime}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">网络类型</div>
							<div class="info-text">
								{props.detail?.modem?.find((item: any) => (item ? true : false))?.netType || props.detail.networkType}
							</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">SIM</div>
							<div class="info-text">{props.detail?.modem?.[0] ? "SIM-1" : "SIM-2"}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">SINR</div>
							<div class="info-text">{props.detail?.modem?.find((item: any) => (item ? true : false))?.sinr}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">RSRP</div>
							<div class="info-text">{props.detail?.modem?.find((item: any) => (item ? true : false))?.rsrp}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">RSRQ</div>
							<div class="info-text">{props.detail?.modem?.find((item: any) => (item ? true : false))?.rsrq}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">MEID</div>
							<div class="info-text">
								{props.detail?.modem?.find((item: any) => (item ? true : false))?.meid || props.detail.meid || "--"}
							</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">ICCID</div>
							<div class="info-text">
								{props.detail?.modem?.find((item: any) => (item ? true : false))?.iccid || props.detail.iccid}
							</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">IMEI</div>
							<div class="info-text">
								{props.detail?.modem?.find((item: any) => (item ? true : false))?.imei || props.detail.imei}
							</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">IMSI</div>
							<div class="info-text">
								{props.detail?.modem?.find((item: any) => (item ? true : false))?.imsi || props.detail.imsi}
							</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">IP</div>
							<div class="info-text">
								{props.detail?.modem?.find((item: any) => (item ? true : false))?.ip || props.detail.ip}
							</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">DTU ID</div>
							<div class="info-text">{props.detail.dtuId}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">Hostname</div>
							<div class="info-text">{props.detail.hostname}</div>
						</div>
					</div>
				</>
			);
		};
	}
});
const Network = defineComponent({
	props: {
		detail: {
			type: Object as PropType<{ [key: string]: any } | any>,
			default() {
				return {};
			}
		}
	},
	emits: ["loadMore"],
	setup(props, { emit }) {
		const state = reactive({
			lanList: [] as any[],
			wanList: [] as any[],
			wlanList: [] as any[],
			modemList: [] as any[]
		});
		watchEffect(() => {
			state.lanList = Array.isArray(props.detail?.lan)
				? props.detail?.lan.filter((lan: any) => (lan ? true : false))
				: props.detail?.lan
				? [props.detail?.lan]
				: [];
			state.wanList = Array.isArray(props.detail?.wan)
				? props.detail?.wan.filter((wan: any) => (wan ? true : false))
				: props.detail?.wan
				? [props.detail?.wan]
				: [];
			state.wlanList = Array.isArray(props.detail?.wlan)
				? props.detail?.wlan.filter((wlan: any) => (wlan ? true : false))
				: props.detail?.wlan
				? [props.detail?.wlan]
				: [];
			state.modemList = Array.isArray(props.detail?.modem)
				? props.detail?.modem.filter((modem: any) => (modem ? true : false))
				: props.detail?.modem
				? [props.detail?.wlamodemn]
				: [];
		});
		return () => {
			return (
				<>
					{/* <div class="flex justify-between item.scss-center">
						<span class="block-title">网络信息</span>
					</div> */}
					{state.lanList.length
						? state.lanList.map((lan: any, i: number) => {
								return (
									<>
										<div class="flex justify-between items-center">
											<div class="block-title">LAN{state.lanList.length > 1 ? `${i + 1}` : ""}</div>
										</div>
										<div class="grid grid-cols-3">
											<div class="flex item">
												<div class="info-title text-right w-1/3">Name</div>
												<div class="info-text">{lan.name}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">IP</div>
												<div class="info-text">{lan.ip || "--"}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">IPV6</div>
												<div class="info-text">{lan.ipv6 || "--"}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">MAC</div>
												<div class="info-text">{lan.mac}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">状态</div>
												<div class="info-text">{lan.status}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3"></div>
												<div class="info-text"></div>
											</div>
										</div>
									</>
								);
						  })
						: null}

					{state.wanList.length
						? state.wanList.map((wan: any, i: number) => {
								return (
									<>
										<div class="flex justify-between items-center">
											<div class="block-title">WAN{state.wanList.length > 1 ? `-${i + 1}` : ""}</div>
										</div>
										<div class="grid grid-cols-3">
											<div class="flex item">
												<div class="info-title text-right w-1/3">Name</div>
												<div class="info-text">{wan.name}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">IP</div>
												<div class="info-text">{wan.ip || "--"}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">IPV6</div>
												<div class="info-text">{wan.ipv6 || "--"}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">MAC</div>
												<div class="info-text">{wan.mac}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">状态</div>
												<div class="info-text">{wan.status}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">MODE</div>
												<div class="info-text">{wan.mode}</div>
											</div>
										</div>
									</>
								);
						  })
						: null}

					{state.wlanList.length
						? state.wlanList.map((wlan: any, i: number) => {
								return (
									<>
										<div class="flex justify-between items-center">
											<div class="block-title">WLAN{state.wlanList.length > 1 ? `-${i + 1}` : ""}</div>
										</div>
										<div class="grid grid-cols-3">
											<div class="flex item">
												<div class="info-title text-right w-1/3">Name</div>
												<div class="info-text">{wlan.name}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">IP</div>
												<div class="info-text">{wlan.ip || "--"}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">IPV6</div>
												<div class="info-text">{wlan.ipv6 || "--"}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">MAC</div>
												<div class="info-text">{wlan.mac}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">状态</div>
												<div class="info-text">{wlan.status}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">SSID</div>
												<div class="info-text">{wlan.ssid}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">Manufacturer</div>
												<div class="info-text">{wlan.manufacturer}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">Model</div>
												<div class="info-text">{wlan.model}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">StaNum</div>
												<div class="info-text">{wlan.staNum}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3"></div>
												<div class="info-text"></div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3"></div>
												<div class="info-text"></div>
											</div>
										</div>
									</>
								);
						  })
						: null}

					{state.modemList.length
						? state.modemList.map((modem: any, i: number) => {
								return (
									<>
										<div class="flex justify-between items-center">
											<div class="block-title">Modem{state.modemList.length > 1 ? `-${i + 1}` : ""}</div>
										</div>
										<div class="grid grid-cols-3">
											<div class="flex item">
												<div class="info-title text-right w-1/3">网络类型</div>
												<div class="info-text">{modem.netType}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">IP</div>
												<div class="info-text">{modem.ip}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">运营商</div>
												<div class="info-text">{modem.operator}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">RSRQ</div>
												<div class="info-text">{modem.rsrq}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">RSRP</div>
												<div class="info-text">{modem.rsrp}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">SINR</div>
												<div class="info-text">{modem.sinr}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">接收</div>
												<div class="info-text">{formatSizeAndUnit(modem.totalRx)}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">发送</div>
												<div class="info-text">{formatSizeAndUnit(modem.totalTx)}</div>
											</div>
											<div class="flex item">
												<div class="info-title text-right w-1/3">总流量</div>
												<div class="info-text">{formatSizeAndUnit(modem.totalRx + modem.totalTx)}</div>
											</div>
										</div>
									</>
								);
						  })
						: null}
				</>
			);
		};
	}
});
const System = defineComponent({
	props: {
		detail: {
			type: Object as PropType<any>,
			default() {
				return {};
			}
		}
	},
	emits: ["loadMore"],
	setup(props, { emit }) {
		return () => {
			return (
				<>
					<div class="flex justify-between items-center">
						<span class="block-title">系统状态</span>
					</div>
					<div class="grid grid-cols-3">
						<div class="flex item">
							<div class="info-title text-right w-1/3">OS</div>
							<div class="info-text">{props.detail?.ostype}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">CPU</div>
							<div class="info-text">{props.detail?.sysresource?.cpuRate || "0"}%</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">磁盘</div>
							<div class="info-text">{props.detail?.sysresource?.diskRate || "0"}%</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">内存</div>
							<div class="info-text">
								<span>{props.detail?.sysresource?.memRate || "0"}% </span>
							</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">MemBuffer</div>
							<div class="info-text">
								<span>{props.detail?.sysresource?.memBuffer} </span>
							</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">MemFree</div>
							<div class="info-text">
								<span>{props.detail?.sysresource?.memFree} </span>
							</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">MCU</div>
							<div class="info-text">{props.detail.mcu}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">软件版本</div>
							<div class="info-text">{props.detail.softver}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">硬件版本</div>
							<div class="info-text">{props.detail.hardwareversion}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">Boot</div>
							<div class="info-text">{props.detail?.sysversion?.boot}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">Rootfs</div>
							<div class="info-text">{props.detail?.sysversion?.rootfs}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">Kernel</div>
							<div class="info-text">{props.detail?.sysversion?.kernel}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">Web</div>
							<div class="info-text">{props.detail?.sysversion?.web}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">Appversion</div>
							<div class="info-text">{props.detail?.sysversion?.appversion}</div>
						</div>
						<div class="flex item">
							<div class="info-title text-right w-1/3">Patches</div>
							<div class="info-text">{props.detail?.sysversion?.patches?.join(",")}</div>
						</div>
					</div>
				</>
			);
		};
	}
});
